package os;

import java.util.Arrays;
import java.util.Scanner;

/**
 * @author mubei
 * @date 2021/12/8
 * @description
 */
public class FIFO {

    final int N = 100;
    int virtualMemory[];
    int size;
    int index = 0;
    int pointer = 0;
    int arr[] = new int[N];
    int map[][];
    char identifying[] = new char[N];

    public FIFO(int size) {
        this.size = size;
        virtualMemory = new int[size];
        map = new int[size][N];
        Arrays.fill(virtualMemory, -1);
        Arrays.fill(identifying, '×');
        //✓
    }

    public void calc() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("输入若干页面 #号结束");
        while (!scanner.hasNext("#")) {
            if (index > 0) {
                for (int i = 0; i < size; i++) {
                    map[i][index] = map[i][index - 1];
                }
            }
            int page = scanner.nextInt();
            // 判断页面是否已经存在
            arr[index] = page;
            boolean isExist = false;
            for (int i : virtualMemory) {
                if (i == page) {
                    isExist = true;
                    break;
                }
            }
            // 如果存在什么都不干
            if (!isExist) {
                if (pointer < size) {
                    virtualMemory[pointer] = page;
                    map[pointer][index] = page;
                    identifying[index] = '✓';
                    pointer++;
                } else {
                    virtualMemory[(pointer) % size] = page;
                    map[pointer%size][index] = page;
                    pointer++;
                    identifying[index] = '✓';
                }
            }
            index++;
        }
       print();
    }

    private void print(){
        for (int i = 0; i < index; i++) {
            System.out.print(arr[i]+"\t");
        }
        System.out.println();
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < index; j++) {
                System.out.print(map[i][j]+"\t");
            }
            System.out.println();
        }
        for (int i = 0; i < index; i++) {
            System.out.print(identifying[i]+"\t");
        }
        System.out.println();
        System.out.println("一共替换 "+pointer+"次");
    }

}
